<template>
  <div class="rolePage">
    <div
      id="main"
      style="
        width: 90%;
        height: 200px;
        border: 1px solid pink;
        background: #183656;
      "
    ></div>

    <el-button type="primary" @click="handleAdd"> 新增角色 </el-button>

    <el-button type="success" @click="toExport"> 导出 </el-button>

    <!-- <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
    >
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload> -->

    <el-table
      :data="
        JSON.parse(JSON.stringify(roleList)).filter(
          (el) =>
            !search || el.label.toLowerCase().includes(search.toLowerCase())
        )
      "
      class="elTable"
      row-key="id"
      border
      default-expand-all
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="id" label="id" align="center" sortable width="70">
        <template #defauilt="{ row }">
          {{ row.id ? row.id : '-' }}
        </template>
      </el-table-column>

      <el-table-column prop="label" label="名称" align="center" sortable>
        <template #defauilt="{ row }">
          {{ row.label ? row.label : '-' }}
        </template>
      </el-table-column>

      <!-- key -->
      <el-table-column prop="key" label="key标识" align="center" sortable>
        <template v-slot="{ row }">
          {{ row.key ? row.key : '' }}
        </template>
      </el-table-column>

      <!-- 建立日期 -->
      <el-table-column
        prop="createTime"
        label="建立日期"
        align="center"
        sortable
        min-width="90"
      >
        <template #defauilt="{ row }">
          {{ row.createTime ? row.createTime : '-' }}
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column align="center" min-width="100">
        <template slot="header">
          <el-input
            class="inputs"
            v-model="search"
            size="mini"
            placeholder="输入姓名搜索"
            clearable
            @clear="search = ''"
          >
          </el-input>
        </template>

        <template slot-scope="scope">
          <el-button
            size="mini"
            :disabled="
              ['0', '1', '2', '3'].includes(scope.row.id) ? true : false
            "
            @click="handleEdit(scope.$index, scope.row, 'edit')"
          >
            编辑
          </el-button>

          <el-button
            size="mini"
            type="danger"
            :disabled="
              ['0', '1', '2', '3'].includes(scope.row.id) ? true : false
            "
            @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="新增"
      :before-close="closeRoleVisible"
      :visible.sync="roleVisible"
      center
      width="600"
    >
      <el-form
        ref="forme"
        :rules="roleRules"
        :model="roleForms"
        label-width="80px"
      >
        <el-form-item label="id">
          <el-input v-model.trim="roleForms.id" disabled></el-input>
        </el-form-item>

        <el-form-item label="名称">
          <el-input v-model.trim="roleForms.label"></el-input>
        </el-form-item>

        <el-form-item label="key标识">
          <el-input v-model.trim="roleForms.key"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeRoleVisible">取 消</el-button>
        <el-button type="primary" @click="onSubmit('forme')"> 确 定 </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapState } from 'vuex'
import roleInfo from './role.js'

export default {
  name: 'role',
  components: {},
  props: {},
  data() {
    return {
      search: '',
      actRoles: [],
      roleVisible: false,
      roleForms: {
        id: '',
        label: '',
        key: '',
        createTime: '2022-12-15 12:00:',
      },
      roleRules: {
        // label: [
        //   { required: true, message: '请输入账号', trigger: 'change' },
        //   { validator: checkUser, trigger: 'blur' },
        // ],
      },
      fileList: [],
      flag: false,
      type: '',
      rows: {},
      index: '',

      imageUrl: '',
    }
  },
  computed: {
    ...mapState(['user']),

    roleList() {
      const lists =
        this.user?.roleList?.length > 0 ? this.user.roleList : roleInfo
      // lists.forEach((el) => {
      //   if (!el.checked) {
      //     el.checked = ['首页', '个人中心']
      //   }
      // })
      return lists
    },
  },
  watch: {
    search: {
      handler(newValue, old) {},
      immediate: true,
      deep: true,
    },
  },
  created() {},
  mounted() {
    this.initEchart()

    // if (window.FileReader) {
    //   var fr = new FileReader()
    //   // add your code here
    // } else {
    //   alert('Not supported by your browser!')
    // }
  },
  methods: {
    initEchart() {
      const initEcharts = echarts.init(document.getElementById('main'))

      // legend
      const XArr = ['待交付(个)', '已交付(个)'],
        warnValue = 100
      let maxData = [60, 60, 60, 60, 60],
        maxValue = 60
      // 第一条数据
      let data1 = [125, 112, 113, 112]
      let oneData = data1.map((item) => {
        return maxValue - item
      })
      console.log('oneData', oneData)
      // 第二条数据
      let data2 = [236, 332, 234, 332]
      let twoData = data2.map((item) => {
        return maxValue - item
      })
      console.log('twoData', twoData)
      // 黄色
      const colors = [
        {
          type: 'linear',
          x: 1,
          y: 0,
          x2: 0,
          y2: 0,
          colorStops: [
            {
              offset: 0,
              color: '#EED743',
            },
            {
              offset: 0.5,
              color: '#D6B628',
            },
            {
              offset: 0.5,
              color: '#B59819',
            },
            {
              offset: 1,
              color: '#DABB35',
            },
          ],
        },
      ]
      // 蓝色
      const colorsPlan = [
        {
          type: 'linear',
          x: 1,
          y: 0,
          x2: 0,
          y2: 0,
          colorStops: [
            {
              offset: 0,
              color: '#68F4EF',
            },
            {
              offset: 0.5,
              color: '#37D6E5',
            },
            {
              offset: 0.5,
              color: '#19A5B5',
            },
            {
              offset: 1,
              color: '#35C2DA',
            },
          ],
        },
      ]
      //透明背景柱子颜色
      const colorsBg = [
        {
          type: 'linear',
          x: 1,
          y: 0,
          x2: 0,
          y2: 0,
          colorStops: [
            {
              offset: 0,
              color: 'rgba(255,255,255,.12)',
            },
            {
              offset: 0.5,
              color: 'rgba(255,255,255,.4)',
            },
            {
              offset: 0.5,
              color: 'rgba(255,255,255,.12)',
            },
            {
              offset: 1,
              color: 'rgba(255,255,255,.4)',
            },
          ],
        },
      ]
      //透明背景柱子顶部颜色
      const colorsTopBg = '#252f31'
      let barWidth = 26,
        labelXPosition = 1,
        symbolSizeTop = 8,
        symbolOffsetX = 16
      const options = {
        grid: {
          left: '10%',
          right: '10%',
          bottom: '7%',
          top: '1%',
          containLabel: false,
        },
        xAxis: {
          show: false,
          type: 'value',
          axisTick: {
            show: false,
          },
          // 坐标轴刻度 在图表方向 并且显示
          splitLine: {
            show: false,
          },
          // 坐标轴线条配置
          axisLine: {
            show: false, // 显示y轴轴线
          },
        },

        yAxis: {
          type: 'category',
          axisTick: {
            show: false,
          },
          // 坐标轴刻度 在图表方向 并且显示
          splitLine: {
            show: false,
          },
          // 坐标轴线条配置
          axisLine: {
            show: false, // 显示y轴轴线
          },
          splitLine: {
            show: false,
          },
          data: XArr,
        },
        series: [
          {
            barWidth: '50',
            // barGap: '50%',

            data: [
              {
                value: 100,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                    {
                      offset: 0,
                      color: 'rgba(255, 209, 92, 1)',
                    },
                    {
                      offset: 1,
                      color: 'rgba(255, 209, 92, 0)',
                    },
                  ]),
                },
                label: {
                  show: true,
                  position: 'right',
                  formatter: '{c}',
                  color: '#fff',
                  fontSize: 20,
                  fontWeight: 800,
                  offset: [10, 0, 0, 0],
                },
              },
              {
                value: 200,
                itemStyle: {
                  color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                    {
                      offset: 0,
                      color: 'rgba(7, 221, 250, 1)',
                    },
                    {
                      offset: 1,
                      color: 'rgba(7, 221, 250, 0)',
                    },
                  ]),
                },
                label: {
                  show: true,
                  position: 'right',
                  formatter: '{c}',
                  color: '#fff',
                  fontSize: 20,
                  fontWeight: 800,
                  offset: [10, 0, 0, 0],
                },
              },
            ],
            type: 'bar',
          },
        ],
      }
      options && initEcharts.setOption(options)
    },

    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },

    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },

    handleAdd() {
      this.roleForms.id = this.roleList.length
      this.roleForms.label = '角色' + `${Number(this.roleList.length) - 2}`
      this.roleForms.key = 'user' + `${Number(this.roleList.length) - 2}`
      this.roleVisible = true
    },

    handleEdit(index, row, type) {
      this.type = type
      this.rows = row
      this.index = index

      this.roleForms.id = index
      this.roleForms.label = 'edit_' + row.label
      this.roleForms.key = 'edit_' + row.key
      this.roleVisible = true
    },

    handleDelete(index, row) {
      this.roleList.splice(index, 1)
      this.$store.commit('setRoleList', this.roleList)
    },

    clearHandler(e) {
      console.log('e', e)
    },

    onSubmit(formName) {
      if (this.flag) return

      this.flag = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const createTime = new Date().toLocaleString()

          const data = {
            ...this.roleForms,
            createTime,
          }

          if (this.type == 'edit') {
            this.$set(this.roleList, this.index, data)

            this.$store.commit('setRoleList', this.roleList)
          } else {
            const lists =
              this.user?.roleList?.length > 0 ? this.user.roleList : roleInfo

            const userLogin = [...lists, data]
            const data2 = ['首页', '个人中心']

            this.$set(userLogin[this.roleList.length], 'checked', data2)

            this.$store.commit('setRoleList', userLogin)
          }

          this.flag = false

          this.roleVisible = false

          this.roleForms = {}
          this.type = ''
          this.index = ''
        }
      })
    },

    closeRoleVisible() {
      this.roleVisible = false
      this.roleForms = {}
      this.type = ''
      this.index = ''
    },

    toExport() {
      const headers = {
        Id: 'id',
        名称: 'label',
        key标识: 'key',
        建立日期: 'createTime',
      }

      import('../../../components/Export2Excel/Export2Excel.js').then(
        (excel) => {
          const data = this.formatJson(headers, this.roleList)
          excel.export_json_to_excel({
            header: Object.keys(headers), //表头 必填
            data: data, //具体数据 必填
            filename: '测试导出列表', //非必填
            autoWidth: true, //非必填
            bookType: 'xlsx', //非必填
          })
        }
      )
    },

    formatJson(headers, rows) {
      //    return rows.map(item => {
      //   return Object.keys(headers).map(key => {
      //     if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
      //       return formatDate(item[headers[key]]) // 返回格式化之前的时间
      //     } else if (headers[key] === 'formOfEmployment') {
      //       var en = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
      //       return en ? en.value : '未知'
      //     }
      //     return item[headers[key]]
      //   }) // => ["张三", "13811"，"2018","1", "2018", "10002"]
      // })

      return rows.map((item) => {
        // item是对象  => 转化成只有值的数组 => 数组值的顺序依赖headers  {username: '张三'  }
        // Object.keys(headers)  => ["姓名", "手机号",...]
        return Object.keys(headers).map((key) => {
          return item[headers[key]]
        }) // /  得到 ['张三'，’129‘，’dd‘,'dd']
      })
    },
  },
}
</script>

<style lang="scss">
.rolePage {
  // height: 100%;
  // margin: 16px;
  font-weight: 800;
  .elTable {
    width: 100%;
    border-radius: 6px;
    margin-top: 15px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.el-popover {
  min-width: 100px;
}

:deep(.el-popover) {
  min-width: 100px;
}

.inputs {
  width: 60%;
}
</style>
